import { Message } from 'element-ui'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // 导入进度条插件
import 'nprogress/nprogress.css' // 导入样式
// import { asyncRoutes } from './router'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userInfo.id) {
        // await store.dispatch('user/getUserInfo')
        const menus = await store.dispatch('user/getUserInfo')
        // const routes = asyncRoutes.filter(v => menus.includes(v.name))
        const routes = await store.dispatch('permission/getRoutes', menus)
        router.addRoutes(routes)
        next(to)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.error({
        showClose: true,
        center: true,
        type: 'error',
        message: '请先登录' })
      NProgress.done()
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
